// pages/post/post.js
const app = getApp();
let api = require("../../utils/api.js")

var COS = require('../../utils/cos-wx-sdk-v5.js')
var cos;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    location: null,
    images: [],
    content: '',
    imgid: 0,
    realList: [],
    TmpSecretId:'',
    TmpSecretKey: '',
    XCosSecurityToken: '',
    ExpiredTime: '',
    cos_img_list :[],
    temp_img_list:[]

  },
  //取消
  saveEditOrNot(){
    wx.navigateBack({
      delta:1
     })
  },

  //与输入内容双向绑定
  getInputValue(e){
    // console.log(this.data.cos_img_list)
    
    this.setData({
      content: e.detail.value,    //与desc双向绑定
    })
    // console.log(this.data.content)
  },
  
  //获取图片
  chooseImage(){
    wx.chooseMedia({
      count: 9,
      mediaType: ['image','video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success:(result)=>{
        // console.log(result.tempFiles[0].tempFilePath)
        // console.log(result.tempFiles)
        console.log(result.tempFiles)
          this.setData({
            images: result.tempFiles
          })  
          this.post()
      }
    })
  },

  //预览图片
  ViewImage(e){

    let src=e.currentTarget.dataset.src;
    let url_list=e.currentTarget.dataset.url;
    var imgList = []; 
    for (let i = 0; i < url_list.length; i++) {
      imgList.push(url_list[i].tempFilePath);
    }
    wx.previewImage({
      current:src, //当前显示图片的http链接
      urls: imgList,  //链接列表
    })
  },


  //发表
  post(){
    var images = this.data.images
    var token = wx.getStorageSync('token')
    let that = this
    cos = new COS({
      getAuthorization: function (options, callback) {
        wx.request({
          url: api.GetTengXunMiYao,
          header:{'Authorization':'JWT'+' '+token},
          success: function (result) {
            var data = result.data.date;
            var credentials = data.credentials;
            callback({
              TmpSecretId: credentials.tmpSecretId,
              TmpSecretKey: credentials.tmpSecretKey,
              XCosSecurityToken: credentials.sessionToken,
              ExpiredTime: data.expiredTime,
            });
          }
        });
      }
    });
      //发送到腾讯云
    for(var index in this.data.images){
      let imageFilePath = images[index].tempFilePath;//   图片连接
      // console.log(imageFilePath)
      var filePathSplit = imageFilePath.split('.');
      var ext = filePathSplit[filePathSplit.length - 1];
      // 创建随机字符串
      let randowString = Math.random().toString(36).slice(-8) + String(new Date().getTime());
      // 唯一：key
      let fileKey = randowString + "." + ext;   //图片链接

      // console.log(fileKey,'>>>>>')
    (function (images,index) {

      cos.postObject({
        Bucket: 'youzhu-1318016344',
        Region: 'ap-hongkong',
        Key: fileKey, 
        FilePath: imageFilePath,
        onProgress: (info) => {
          console.log('info', info)
          that.setData({
            ["images[" + index + "].percent"]: info.percent * 100,
            ["images[" + index + "].key"]: fileKey,
          })

        }
      }, (err, data) => {
        // 上传成功或失败
        if (err) {
          // console.log(err,'>>>>>>>')
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
          that.setData({
            ["images[" + index + "].error"]: true,
            ["images[" + index + "].percent"]: 100
          })
          return false
        } else {
          // console.log(data,'>>>data>>>>>')
          // that.setData({
          //   cos_img_list:that.data.cos_img_list.concat(data.headers.location)
          // })
          // console.log(data.headers.location)
          // images[index].tempFilePath = data.headers.location
          that.setData({
            temp_img_list :that.data.temp_img_list.concat(data.headers.location),
            ["images["+index+"].tempFilePath"] : data.headers.location
          })
        }
      });
    })(this.data.images,index)
    }
      },

// 发表
  send:function (params) {
      
        console.log(this.data.temp_img_list.length,'temp_img_list')
        console.log(this.data.images.length,'images')
        if (this.data.temp_img_list.length != this.data.images.length){
          wx.showToast({
            title: '图片上传中！',
            'icon':'error'
          })
          return
        }

        for (var index in this.data.images){
          let imageFilePath =  this.data.images[index].tempFilePath;//   图片连接
          this.setData({
            cos_img_list:this.data.cos_img_list.concat(imageFilePath)
          })
        }
        var token = wx.getStorageSync('token')
        var text = this.data.content
        var tempFilePaths =this.data.cos_img_list
        wx.request({
          url: api.PublishCustom,
          data:{
            desc:text,
            photo:tempFilePaths
          },
          method:"POST",
          header:{'Authorization':'JWT'+' '+token},
          success:result=>{
            if(result.data.code==100){
              wx.navigateBack({
                delta:1
               })
          }
          }
        
      })},


   // 点击删除图片
   removeImage: function (event) {
    // 判断是否正在上传，如果正在上传就终止，否则就删除；
    // 删除图片，终止 & 删除
    wx.showToast({
      title: '请稍等',
      icon: 'none'
    })
    var index = event.currentTarget.dataset['index'];
    var item = event.currentTarget.dataset['item'];
    if (item.percent == 100) {
      cos.deleteObject({
        Bucket: 'youzhu-1318016344',
        Region: 'ap-hongkong',
        Key: item.key
      }, (err, data) => {
        if (err) {
          wx.showToast({
            title: '删除失败',
            icon: 'none'
          });
        } else {
          var imageList = this.data.images;
          // 删除发后端的数据
          imageList.splice(index, 1);
          console.log(item,"item")
          // 删除temp临时数据
          let del_path = item.tempFilePath
          let new_temp_list = this.data.temp_img_list
          new_temp_list = new_temp_list.filter(items => items !== del_path);
          this.setData({
            images: imageList,
            temp_img_list:new_temp_list
          });
          // console.log(new_temp_list,'new_temp_list')
          // console.log(del_path,'new_temp_list')
          // console.log(imageList,'imageList')
          wx.showToast({
            title: '删除成功',
            icon:'success'
          })
        }
      });
    }

  },






  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})
